package init

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"shop-srv/basic/config"
	"shop-srv/handler/models"
	"sync"
	"time"
)

var err error

func initm() {
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	Mysqlconfig := config.Appcon.Mysql
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		Mysqlconfig.User,
		Mysqlconfig.Password,
		Mysqlconfig.Host,
		Mysqlconfig.Port,
		Mysqlconfig.Database)
	once := sync.Once{} //单例模式
	once.Do(func() {
		config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})

	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据库连接成功")
	}
	err := config.DB.AutoMigrate(&models.User{}, &models.Shop{}, &models.Shopwindow{}, &models.ShopwindowCargetry{}, &models.Order{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("迁移成功")
	}
	sqlDB, _ := config.DB.DB() //mysql连接池

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
}
